package settinghandler

import (
	"encoding/json"
	"errors"
	"github.com/gin-gonic/gin"
	"io/ioutil"
	"net/http"
	"yundian/internel/app/dao"
	"yundian/internel/app/models/regions"
	"yundian/internel/pkg/dingo"
)

func GetRegions(ctx *gin.Context)  {
	result,err := GetRegionData() // 获取
	dingo.ErrorIf(err, result).Unwrap()
	// 插入数据库表
	res := dao.NewSettingDao().InsertRegion(result).Unwrap().(bool)
	if res {
		// 更新层级
		dao.NewSettingDao().UpdateRegion("[1-9][0-9]0000", "", 0, 1)                // 处理省级：只需要将省级 level 更新为 1
		dao.NewSettingDao().UpdateRegion("[1-9][0-9]{3}00", "[0-9]{2}00", 10000, 2) // 处理地级市：更新市级 level 为 2、parent 为其上级 region_id
		dao.NewSettingDao().UpdateRegion("[1-9][0-9]{3}00", "[0-9]{2}", 100, 3)     // 处理区县：更新区县 level 为 3、parent 为其上级 region_id
		dao.NewSettingDao().UpdateRegion("[1-9][0-9]{3}00", "[0-9]{4}", 10000, 2)   // 处理县级市：更新市级 level 为 2、parent 为其上级 region_id
	}
}

// 获取 Region
func GetRegionData() (*regions.TencentRegionsResult, error) {
	resp, err := http.Get("http://apis.map.qq.com/ws/district/v1/list?key=Y53BZ-S3WW4-CCBUI-DHJ73-4RNNS-RBBEN&output=json")
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}
	var rg *regions.TencentRegionsResult
	err = json.Unmarshal(body, &rg)
	if err != nil {
		return nil, err
	}
	if rg.Status != 0 {
		return nil, errors.New(rg.Message)
	}

	return rg, nil
}
